<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @keyup.enter.native="search()"
    >
      <el-form-item label="活动编码">
        <br />
        <br />
        <el-input
          style="margin-left: -70px; width: 200px"
          v-model="formInline.activityCode"
          placeholder
        >
        </el-input>
      </el-form-item>

      <el-form-item label="活动名称">
        <br />
        <br />
        <el-input
          style="margin-left: -70px; width: 200px"
          v-model="formInline.activityName"
          placeholder
        >
        </el-input>
      </el-form-item>
      <el-form-item label="发布状态">
        <br />
        <br />
        <el-select
          style="margin-left: -70px; width: 200px"
          v-model="formInline.publishStatus"
        >
          <el-option label="全部" value></el-option>
          <el-option label="已发布" value="1"></el-option>
          <el-option label="未发布" value="0"></el-option>
        </el-select>
      </el-form-item>
      <!--            <el-form-item label="开展状态">-->
      <!--              <br> <br>-->
      <!--                <el-select style="margin-left:-70px;width:200px" v-model="formInline.runStatus">-->
      <!--                    <el-option label="全部" value></el-option>-->
      <!--                    <el-option label="未开始" value="1"></el-option>-->
      <!--                    <el-option label="进行中" value="2"></el-option>-->
      <!--                    <el-option label="已结束" value="3"></el-option>-->
      <!--                </el-select>-->
      <!--            </el-form-item>-->
      <br />
      <el-form-item label="活动时间">
        <br />
        <br />
        <el-date-picker
          style="margin-left: -70px; width: 405px"
          v-model="formInline.runTimeRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间">
        <br />
        <br />
        <el-date-picker
          style="margin-left: -70px; width: 410px"
          v-model="formInline.createTimeRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <div style="width: 100%; display: flex; justify-content: flex-end">
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="search()"
            size="mini"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="kong()"
            size="mini"
            icon="el-icon-delete"
            >清空</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="toAdd()"
            icon="el-icon-edit"
            size="mini"
            >创建活动</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      height="400px"
      style="width: 100%"
      :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
    >
      <el-table-column
        type="index"
        width="60"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        v-for="(item, index) in col"
        :key="`col_${index}`"
        show-overflow-tooltip
        :prop="dropCol[index].prop"
        :width="dropCol[index].width"
        :label="item.label"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="dropCol[index].prop === 'publishStatus'">
            <span v-if="scope.row.publishStatus == '0'">未发布</span>
            <span v-if="scope.row.publishStatus == '1'">已发布</span>
          </div>
          <div
            v-if="dropCol[index].prop === 'activityModificationRecordQuantity'"
          >
            <span v-if="scope.row.activityModificationRecordQuantity != null">
              <a
                style="color: blue; cursor: pointer"
                @click="
                  () => {
                    showRecord = true;
                    recordActivityCode = scope.row.activityCode;
                  }
                "
              >
                {{ scope.row.activityModificationRecordQuantity }}
              </a>
            </span>
            <span v-if="scope.row.activityModificationRecordQuantity == null"
              >—</span
            >
          </div>
          <div v-if="dropCol[index].prop === 'type'">
            <span v-if="scope.row.type == '1'">未开始</span>
            <span v-if="scope.row.type == '2'">进行中</span>
            <span v-if="scope.row.type == '3'">已结束</span>
          </div>
          <div v-if="dropCol[index].prop === 'yxq'">
            <span v-if="scope.row.beginDate != null">
              {{ scope.row.beginDate + ' — ' + scope.row.endDate }}
            </span>
            <span v-if="scope.row.beginDate == null">—</span>
          </div>
          <div v-if="dropCol[index].prop === 'joinStatus'">
            <span v-if="scope.row.joinCount != null">
              <a
                @click="seedetail(scope.row)"
                style="color: blue; cursor: pointer"
              >
                {{ scope.row.joinCount + ' / ' + scope.row.orgCount }}
              </a>
            </span>
            <span v-if="scope.row.joinCount == null">—</span>
          </div>
          <div v-if="dropCol[index].prop === 'activityDesc'">
            <span v-if="scope.row.activityDesc != null">
              {{ scope.row.activityDesc.replace(/<[^>]+>/g, '') }}
            </span>
            <span v-if="scope.row.activityDesc == null">—</span>
          </div>
          <div
            v-if="
              dropCol[index].prop != 'activityDesc' &&
                dropCol[index].prop != 'publishStatus' &&
                dropCol[index].prop != 'type' &&
                dropCol[index].prop != 'yxq' &&
                dropCol[index].prop != 'activityModificationRecordQuantity'
            "
          >
            {{ scope.row[dropCol[index].prop] }}
          </div>
        </template>
      </el-table-column>
      <!--
      <el-table-column
          prop="activityCode"
          label="预售活动编码"
          align="center"
          width="150"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="activityName"
          label="预售活动名称"
          header-align="center"
          width="200"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="activityDesc"
          label="活动描述"
          header-align="center"
          align="left"
          width="250"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="发布状态" align="center" width="150">
          <template slot-scope="scope">
              <span v-if="scope.row.publishStatus == '0'">未发布</span>
              <span v-if="scope.row.publishStatus == '1'">已发布</span>
          </template>
      </el-table-column>
      <el-table-column label="开展状态" align="center" width="150">
          <template slot-scope="scope">
              <span v-if="scope.row.type == '1'">未开始</span>
              <span v-if="scope.row.type == '2'">进行中</span>
              <span v-if="scope.row.type == '3'">已结束</span>
          </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" width="250" :formatter="dateRange"></el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="150"
      ></el-table-column>
      <el-table-column prop="createUserName" label="创建人" align="center" width="120"></el-table-column>
      -->
      <el-table-column
        label="操作"
        width="200"
        align="center"
        header-align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div style="width: 120px; text-align: left; margin: 0 auto">
            <el-button
              type="text"
              @click="toDetail(scope.row)"
              v-if="scope.row.publishStatus == 1"
              >详情
            </el-button>
            <el-button
              type="text"
              @click="toDetail(scope.row)"
              v-if="scope.row.actStatus == 1"
              >详情
            </el-button>
            <el-button type="text" v-if="scope.row.actStatus == 1"
              >已结束</el-button
            >
            <el-button
              type="text"
              @click="toEdit(scope.row)"
              v-if="scope.row.publishStatus == 0 && scope.row.actStatus == 0"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="setActStatus(scope.row.uuid, '1')"
              v-if="scope.row.publishStatus == 0 && scope.row.actStatus == 0"
              >发布
            </el-button>
            <el-button
              type="text"
              @click="setActStatus(scope.row.uuid, '0')"
              v-if="scope.row.publishStatus == 1 && scope.row.actStatus == 0"
              >撤回
            </el-button>
            <el-button
              type="text"
              @click="deleteGoodsActivity(scope.row.uuid)"
              v-if="scope.row.status == '0'"
              >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 5px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="参与详情"
      :visible.sync="dialogVisibledetail"
      width="70%"
      custom-class="el-dialog-star"
      top="3vh"
    >
      <el-form
        :inline="true"
        :model="formCoupon"
        class="search-form-inline"
        style="margin-top: -20px"
      >
        <el-input
          v-model="formCoupon.shopName"
          style="width: 200px"
          placeholder="专卖店名称"
          clearable
        ></el-input>
        <el-input
          v-model="formCoupon.warzoneName"
          style="width: 200px"
          placeholder="大区名称"
          clearable
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="(listQuery2.current = 1), queryJoinStoreInfo()"
          >查询
        </el-button>
        <el-button
          @click="exportExcel"
          style="margin-top: 0px"
          size="mini"
          type="success"
          icon="el-icon-s-data"
          :loading="exportLoading"
          >导出</el-button
        >
      </el-form>
      <el-table
        :data="couponListshop"
        border
        style="font-size: 10px; width: 100%; margin-top: 10px"
        height="300"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="60"
        ></el-table-column>
        <!--<el-table-column prop="couponNo" label="卡券编号" width="200" header-align="center"></el-table-column>-->
        <el-table-column
          prop="authCode"
          label="店铺编码"
          width="120"
          align="left"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="storeName"
          label="专卖店名称"
          width="200"
          align="left"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="upOrgZone"
          label="所属大区"
          width="200"
          align="left"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="storeAddressDetail"
          label="门店地址"
          width="230"
          align="left"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="enterStatus"
          label="报名状态"
          width="120"
          align="left"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.enterStatus == 1 ? '已参加' : '未参加' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="参与时间"
          align="right"
          width="180"
        ></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibledetail = false">取 消</el-button>
        <!-- <el-button type="primary" @click="couponConfirm()">确 定</el-button> -->
      </span>
      <div class="block" style="margin-top: 5px">
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
          :current-page="listQuery2.current"
          :page-size="listQuery2.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        >
        </el-pagination>
      </div>
    </el-dialog>

    <PreSaleActivityRecord
      :show.sync="showRecord"
      :recordActivityCode="recordActivityCode"
    />
  </div>
</template>

<script>
import Sortable from 'sortablejs';
import {
  deleteGoodsActivity,
  queryJoinStoreInfo,
  queryPreSaleActList,
  setActStatus,
  toExcelJoinStore,
} from '@/api/preSaleActivity';
import PreSaleActivityRecord from './components/PreSaleActivityRecord.vue';

const curDateStr = function() {
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : '0' + month;
  var date = curDate.getDate();
  date = date > 9 ? date : '0' + date;
  return year + '-' + month + '-' + date;
};

export default {
  components: {
    PreSaleActivityRecord,
  },
  data() {
    return {
      loading: true,
      uuid: '',
      col: [
        {
          label: '预售活动编码',
          prop: 'activityCode',
          width: '150',
        },
        {
          label: '预售活动名称',
          prop: 'activityName',
          width: '200',
        },
        {
          label: '参与情况',
          prop: 'joinStatus',
          width: '120',
        },
        {
          label: '活动描述',
          prop: 'activityDesc',
          width: '250',
        },
        {
          label: '发布状态',
          prop: 'publishStatus',
          width: '150',
        },
        {
          label: '订阅数量',
          width: '150',
          prop: 'subscriptionQuantity',
        },
        {
          label: '活动修改记录',
          width: '150',
          prop: 'activityModificationRecordQuantity',
        },
        {
          label: '有效期',
          prop: 'yxq',
          width: '350',
        },
        {
          label: '创建时间',
          prop: 'createTime',
          width: '170',
        },
      ],
      dropCol: [
        {
          label: '预售活动编码',
          prop: 'activityCode',
          width: '150',
        },
        {
          label: '预售活动名称',
          prop: 'activityName',
          width: '200',
        },
        {
          label: '参与情况',
          prop: 'joinStatus',
          width: '120',
        },
        {
          label: '活动描述',
          prop: 'activityDesc',
          width: '250',
        },
        {
          label: '发布状态',
          prop: 'publishStatus',
          width: '150',
        },
        {
          label: '订阅数量',
          width: '150',
          prop: 'subscriptionQuantity',
        },
        {
          label: '活动修改记录',
          width: '150',
          prop: 'activityModificationRecordQuantity',
        },
        {
          label: '有效期',
          prop: 'yxq',
          width: '350',
        },
        {
          label: '创建时间',
          prop: 'createTime',
          width: '170',
        },
      ],
      formInline: {
        activityCode: '',
        activityName: '',
        publishStatus: '',
        actStatus: '',
        runStatus: '',
        runTimeRange: '',
        createTimeRange: '',
      },
      listQuery2: {
        current: 1,
        size: 20,
      },
      dialogVisibledetail: false,
      uuid: '',
      couponListshop: [],
      formCoupon: {
        shopName: '',
        warzoneName: '',
      },
      total: 0,
      total2: 0,
      listQuery: {
        current: 1,
        size: 20,
      },
      tableData: [], //活动列表
      pickerOptions: {
        shortcuts: [
          {
            text: '最近3天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
      exportLoading: false,

      // 活动修改记录相关参数
      showRecord: false,
      recordActivityCode: '',
    };
  },
  mounted() {
    this.queryPreSaleActList();

    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    // this.rowDrop()
    this.columnDrop();
  },
  methods: {
    exportExcel() {
      this.exportLoading = true;
      let data = {
        size: 9999,
        current: 1,
        condition: {
          activityId: this.uuid,
          storeName: this.formCoupon.shopName,
          upOrgZone: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      toExcelJoinStore(data)
        .then((res) => {
          this.exportLoading = false;
          const link = document.createElement('a');
          let blob = new Blob([res], {
            type: 'application/vnd.ms-excel',
          });
          link.style.display = 'none';
          //设置连接
          link.href = URL.createObjectURL(blob);
          link.download = '预售活动门店参与列表.xlsx';
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
        })
        .catch((err) => {
          this.exportLoading = false;
          console.log(err);
        });
    },
    seedetail(v) {
      this.formCoupon.shopName = '';
      this.formCoupon.warzoneName = '';
      this.dialogVisibledetail = true;
      this.uuid = v.uuid;
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          activityId: v.uuid,
        },
        ascs: [],
        descs: [],
      };
      queryJoinStoreInfo(data).then((res) => {
        this.couponListshop = res.records;
        this.total2 = res.total;
      });
    },
    queryJoinStoreInfo() {
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          activityId: this.uuid,
          storeName: this.formCoupon.shopName,
          upOrgZone: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryJoinStoreInfo(data).then((res) => {
        this.couponListshop = res.records;
        this.total2 = res.total;
      });
    },
    //拖拽列表
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const oldItem = this.dropCol[evt.oldIndex - 1];
          this.dropCol.splice(evt.oldIndex - 1, 1);
          this.dropCol.splice(evt.newIndex - 1, 0, oldItem);
        },
      });
    },
    //活动列表
    queryPreSaleActList() {
      let creatBeginDate = null;
      let creatEndDate = null;
      if (
        this.formInline.createTimeRange != null &&
        this.formInline.createTimeRange.length == 2
      ) {
        creatBeginDate = this.formInline.createTimeRange[0];
        creatEndDate = this.formInline.createTimeRange[1];
      }
      let beginDate = null;
      let endDate = null;
      if (
        this.formInline.runTimeRange != null &&
        this.formInline.runTimeRange.length == 2
      ) {
        beginDate = this.formInline.runTimeRange[0];
        endDate = this.formInline.runTimeRange[1];
      }
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          activityCode: this.formInline.activityCode.trim(),
          activityName: this.formInline.activityName.trim(),
          publishStatus: this.formInline.publishStatus,
          creatBeginDate: creatBeginDate,
          creatEndDate: creatEndDate,
          type: this.formInline.runStatus,
          beginDate: beginDate,
          endDate: endDate,
        },
        ascs: [],
        descs: [],
      };
      queryPreSaleActList(data).then((res) => {
        this.loading = false;
        this.tableData = res.records;
        this.total = res.total;
      });
    },
    fixData(row, column, cellValue, index) {
      if (cellValue == null || cellValue == '') return '';
      return cellValue.substring(0, 10);
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.queryPreSaleActList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.queryPreSaleActList();
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryJoinStoreInfo();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryJoinStoreInfo();
    },
    //查询
    search() {
      this.listQuery.current = 1;
      this.queryPreSaleActList();
    },
    //清空
    kong() {
      this.formInline.activityCode = '';
      (this.formInline.activityName = ''), (this.formInline.publishStatus = '');
      this.formInline.runStatus = '';
      this.formInline.runTimeRange = '';
      this.formInline.createTimeRange = '';
    },
    //添加活动
    toAdd() {
      this.$router.push({
        name: 'preSaleActivityDetail',
        params: {
          actflag: true,
        },
      });
    },
    //查看活动
    toDetail(item) {
      this.$router.push({
        name: 'preSaleActivityDetail',
        params: {
          edit: item,
          flag: true,
        },
      });
    },
    //编辑活动
    toEdit(item) {
      this.$router.push({
        name: 'preSaleActivityDetail',
        params: {
          edit: item,
          flag: false,
        },
      });
    },
    setActStatus(uuid, status) {
      var msg = '';
      if (status == '1') {
        msg = '发布';
      } else if (status == '0') {
        msg = '撤回';
      }
      this.$confirm('确定' + msg + '当前活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let data = {
            activityId: uuid,
            publishStatus: status,
          };
          setActStatus(data).then((res) => {
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: msg + '成功',
                type: 'success',
              });
              this.queryPreSaleActList();
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: 'error',
              });
            }
            this.loading = false;
          });
        })
        .catch(() => {});
    },
    deleteGoodsActivity(uuid, status) {
      this.$confirm('确定删除当前活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let data = {
            uuid: uuid,
            status: status,
          };
          deleteGoodsActivity(data).then((res) => {
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: '删除成功',
                type: 'success',
              });
              this.queryPreSaleActList();
            } else {
              this.$message.error('删除失败');
            }
            this.loading = false;
          });
        })
        .catch(() => {});
    },
    //数字格式化
    dateRange(row, column, cellValue, index) {
      if (row.beginDate != null && row.beginDate.toString().length >= 10) {
        return (
          row.beginDate.toString().substr(0, 10) +
          ' — ' +
          row.endDate.toString().substr(0, 10)
        );
      } else {
        return '—';
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = false; // C 跳转到 A 时让 A 不缓存，即刷新
    next();
  },
};
</script>
<style lang="less" scoped></style>
